use std::thread;
use std::time::Duration;

use async_io::Timer;
use futures::executor::LocalPool;
use futures::task::LocalSpawnExt;
use orbtk::prelude::*;

use crate::main_view::MainView;

enum Message {
    Increment,
}

#[derive(AsAny, Default)]
pub(crate) struct MainState {
    count: i32,
    my_thread: Option<thread::JoinHandle<()>>,
    // thread_pool: ThreadPool,
}

impl State for MainState {
    fn init(&mut self, _registry: &mut Registry, ctx: &mut Context) {
        let message_adapter = ctx.message_adapter();
        let entity = ctx.widget().entity();

        // increments a counter and send the result as message to `MainView`.
        self.my_thread = Some(thread::spawn(move || {
            let mut pool = LocalPool::new();
            pool.spawner()
                .spawn_local(async move {
                    loop {
                        Timer::after(Duration::from_secs(1)).await;
                        message_adapter.send_message(Message::Increment, entity)
                    }
                })
                .unwrap();

            pool.run();
        }));

        // println!("{:?}hello", thread::current().id());
        // self.my_thread = Some(thread::spawn(move || {
        //     println!("{:?}word", thread::current().id());
        //     block_on(LocalExecutor::new().run(async {
        //         loop {
        //             println!("{:?}thread", thread::current().id());
        //             Timer::after(Duration::from_secs(1)).await;
        //             message_adapter.send_message(Message::Increment, entity)
        //         }
        //     }));
        // }));
    }
    fn messages(
        &mut self,
        mut messages: MessageReader,
        _registry: &mut Registry,
        ctx: &mut Context,
    ) {
        for message in messages.read::<Message>() {
            match message {
                Message::Increment => {
                    self.count += 1;
                    MainView::text_set(&mut ctx.widget(), self.count.to_string());
                }
            }
        }
    }
}
